<template>
  <div class="make-invoice">
    <section class="header">
      <a-page-header
          title="生成开票信息"
          @back="() => $router.go(-1)"
      ></a-page-header>
    </section>

    <a-alert type="info" v-if="!advanceApprove" style="margin: 10px">
      <template #message>
        提前开票暂未开启审批，点击”
        <span
            v-if="advanceis_admin"
            class="link"
            @click.stop="goSetting(advance_id, 1)"
        >配置</span
        >
        <span v-else class="link" style="cursor: not-allowed">配置</span>
        “可快速设置。
      </template>
    </a-alert>

    <a-alert type="info" v-if="!actualApprove" style="margin: 10px">
      <template #message>
        实收开票暂未开启审批，点击”
        <span
            v-if="actualis_admin"
            class="link"
            @click.stop="goSetting(actual_id, 2)"
        >配置</span
        >
        <span v-else class="link" style="cursor: not-allowed">配置</span>
        “可快速设置。
      </template>
    </a-alert>

    <a-card :border="false" class="content" title="当前模板可开票账单">
      <template #extra>
        <a-space>
          <a-select v-model:value="templateId" @change="getInitInvoiceData">
            <a-select-option
                v-for="item of templateList"
                :key="item.id"
                :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
              v-model:value="mergeType"
              @change="getRenderDataList"
              style="width: 200px"
          >
            <a-select-option
                v-for="item of mergeTypeList"
                :key="item.key"
                :value="item.key"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-space>
      </template>
      <a-alert
          class="mb-20"
          type="info"
          show-icon
          v-if="selectedRowKeys.length"
      >
        <template #message>
          <span>已选择</span>
          <span class="mlr-5 text-blue">{{ selectedRowKeys.length }}</span>
          <span>项</span>
          <span class="ml-10">申请开票金额：</span>
          <span class="fw-bold">{{ applyMoneyTotal }}元</span>
        </template>
      </a-alert>
      <a-table
          :dataSource="dataList"
          :columns="COLUMNS"
          :pagination="false"
          :rowSelection="rowSelection"
          :scroll="{ x: 'max-content' }"
          rowKey="key"
          :loading="loading"
      >
        <template #bodyCell="{ text, record, index, column }">
          <!-- 发票抬头 -->
          <template v-if="column.key === 'invoice_title'">
            <a-select
                :value="record.title_id"
                @change="(value) => handleInvoiceChange(value, record, index)"
                style="width: 160px"
                :options="
                record.invoiceList.map((item) => {
                  return {
                    label: item.title,
                    value: item.id,
                  };
                })
              "
            >
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu"/>
                <a-divider style="margin: 4px 0"/>
                <div
                    class="text-center"
                    @mousedown="(e) => e.preventDefault()"
                    @click="addInvoice(record, index)"
                >
                  <a-button type="link">
                    <template #icon>
                      <PlusOutlined/>
                    </template>
                    新增
                  </a-button>
                </div>
              </template>
            </a-select>
          </template>
          <!-- 发票类型 -->
          <template v-if="column.key === 'invoice_type'">
            <a-select
                :value="text"
                @change="(value) => handleInvoiceTypeChange(value, record)"
                style="width: 160px"
            >
              <a-select-option
                  v-for="item of record.invoiceTypeList"
                  :key="item.key"
                  :value="item.key"
                  :disabled="item.disabled"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </template>
          <template v-if="column.key === 'issue_type'">
            <!-- 开票类型 -->
            <a-select
                :value="text"
                :disabled="
                record.can_invoice_amount_type1 <= 0 ||
                record.can_invoice_amount_type2 <= 0
              "
                @change="(value) => handleIssueTypeChange(value, record)"
            >
              <a-select-option
                  v-for="item of issueTypeList"
                  :key="item.key"
                  :value="item.key"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </template>
          <!-- 费用类型  -->
          <template v-if="column.key === 'cost_type_txt'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="item of text"
                  :key="'cost_type_txt_' + item.subbill_id"
                  class="lh-30"
              >
                <span
                >{{ item.cost_type_txt }}
                  <span style="color: #2681f3" v-if="item.is_merge == 0"
                  >（不可合并）</span
                  ></span
                >
              </div>
            </a-space>
          </template>
          <!-- 商品或服务名称 -->
          <template v-if="column.key === 'tax_cost_name'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="item of text"
                  :key="'tax_cost_name_' + item.subbill_id"
                  class="lh-30"
              >
                <span>{{ item.tax_cost_name }}</span>
              </div>
            </a-space>
          </template>
          <!-- 税率 -->
          <template v-if="column.key === 'tax_rate'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="(item, index) of text"
                  :key="'tax_rate_' + item.subbill_id"
                  class="lh-30"
              >
                <a-select
                    :value="item.tax_rate"
                    @change="(value) => handleTaxRateChange(value, record, index)"
                >
                  <a-select-option
                      v-for="item of item.tax_template_rate"
                      :key="item.tax_rate"
                      :value="item.tax_rate"
                  >
                    {{ item.tax_rate_txt }}
                  </a-select-option>
                </a-select>
              </div>
            </a-space>
          </template>
          <!-- 可开票金额 -->
          <template v-if="column.key === 'can_invoice_amount'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="item of text"
                  :key="'can_invoice_amount_' + item.subbill_id"
                  class="lh-30"
              >
                <span>{{ item.can_invoice_amount }}</span>
              </div>
            </a-space>
          </template>
          <!-- 申请开票金额 -->
          <template v-if="column.key === 'apply_invoice_amount'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="(item, index) of text"
                  :key="'apply_invoice_amount_' + item.subbill_id"
                  class="lh-30"
              >
                <a-input-number
                    :value="item.apply_invoice_amount"
                    :min="0"
                    :max="Number(item.can_invoice_amount)"
                    :precision="2"
                    @change="
                    (value) =>
                      handleApplyInvoiceAmountChange(value, record, index)
                  "
                    :disabled="applyInvoiceAmountDisabled"
                    class="w-100p"
                />
              </div>
            </a-space>
          </template>
          <!--  税额 -->
          <template v-if="column.key === 'apply_tax_amount'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="item of text"
                  :key="'tax_amount_' + item.subbill_id"
                  class="lh-30"
              >
                <span>{{ item.tax_amount }}</span>
              </div>
            </a-space>
          </template>
          <template v-if="column.key === 'tax_amount'">
            <a-space direction="vertical" size="middle">
              <div
                  v-for="item of text"
                  :key="'tax_amount_' + item.subbill_id"
                  class="lh-30"
              >
                <span>{{ item.tax_amount }}</span>
              </div>
            </a-space>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="handleInvoiceEdit(record)"
            >编辑
            </a-button
            >
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 确定、返回 -->
    <section class="mt-20 text-right plr-20">
      <a-space>
        <a-button @click="() => $router.go(-1)">取消</a-button>
        <a-button type="primary" @click="confirm">{{
            advanceApprove || actualApprove ? "确定&发起审批" : "确定"
          }}
        </a-button>
      </a-space>
    </section>

    <!-- 编辑 -->
    <edit-invoice
        :visible="editVisible"
        :content="editContent"
        @cancel="editVisible = false"
        @success="handleInvoiceEditSuccess"
    />

    <!-- 新增发票抬头 -->
    <AddInvoice
        :visible="invoiceVisible"
        :ownerId="ownerId"
        @successChange="successChange"
        @closeChange="invoiceVisible = false"
    />
  </div>
</template>

<script>
import {message, Modal} from "ant-design-vue";
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  toRaw,
  createVNode,
  nextTick,
} from "vue";
import {useRoute, useRouter} from "vue-router";
import request from "../../../common/utils/request";
import EditInvoice from "./modules/EditInvoice.vue";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons-vue";
import utils from "@/common/utils/utils";
import AddInvoice from "@/views/village/OwnerManage/modules/AddInvoice.vue";
import store from "@/store";

export default defineComponent({
  name: "makeInvoice",
  components: {
    EditInvoice,
    PlusOutlined,
    VNodes: (_, {attrs}) => {
      return attrs.vnodes;
    },
    AddInvoice,
  },
  setup() {
    const $route = useRoute();
    const $router = useRouter();
    const state = reactive({
      // 所选账单
      billIds: [],
      loading: false,
      // 发票模板选择
      templateId: undefined,
      templateList: [],
      // 账单合并类型
      mergeType: undefined,
      mergeTypeList: [],
      // 表格数据
      dataList: [],
      initDataList: [],
      // invoiceTypeList: [],
      issueTypeList: [],
      currentTaxTemp: {},
      taxRateList: [],
      // 申请开票金额禁止填写
      applyInvoiceAmountDisabled: false,
      // 选择行操作
      selectedRowKeys: [],
      selectedRows: [],
      applyMoneyTotal: 0, // 申请开票的总金额
      // 编辑
      editVisible: false,
      editContent: {},
      e_invoce_type: 0,
      invoce_id: 0,
      template_id: [],

      invoiceVisible: false,
      ownerId: 0,
      invoiceIndex: 0,
      //提前审批
      advanceApprove: false,
      advanceis_admin: false,
      advance_id: "",
      //实际审批
      actualApprove: false,
      actualis_admin: false,
      actual_id: "",
      apptype: "",
      merge: 1,
    });

    /* 选择账单行 */
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
    }));
    const onSelectedRowChange = (keys, rows) => {
      state.selectedRowKeys = keys;
      state.selectedRows = rows;
      getApplyTotalMoney();
    };

    // 选择的模板是否需要审批
    const haveApproval = computed(() => {
      return !!state.templateList.find((v) => v.id == state.templateId)
          ?.is_approval;
    });

    /* 获取申请开票的总金额 */
    const getApplyTotalMoney = () => {
      if (!state.selectedRows.length) {
        state.applyMoneyTotal = 0;
        return;
      }
      let total = 0;
      state.selectedRows.forEach((item) => {
        total = (Number(total) + Number(item.apply_invoice_amount)).toFixed(2);
      });
      state.applyMoneyTotal = total;
    };

    const getCurrentAmountTotal = (current) => {
      const invoiceTotalData = getCanInvoiceAmountTotal(current.splitList);
      for (let key in invoiceTotalData) {
        current[key] = invoiceTotalData[key];
      }
      getApplyTotalMoney();
    };

    /* 监听发票类型变化 */
    const handleInvoiceTypeChange = (value, current) => {
      current.invoice_type = value;
    };

    /* 监听发票抬头变化 */
    const handleInvoiceChange = (value, current) => {
      current.title_id = value;
      current.buyer_name = current.invoiceList.filter(
          (item) => item.id == value
      )[0].title;
      current.company_type = current.invoiceList.filter(
          (item) => item.id == value
      )[0].company_type;
      current.invoiceTypeList = JSON.parse(
          JSON.stringify(current.invoiceTypeList)
      );
      if (current.company_type == 1) {
        current.invoiceTypeList.forEach((invoice) => {
          if (invoice.key == 2) {
            invoice.disabled = true;
            current.invoice_type = current.invoiceTypeList[0].key;
          }
        });
      } else {
        current.invoiceTypeList.forEach((invoice) => {
          invoice.disabled = false;
        });
      }
    };

    // 新增发票抬头
    const addInvoice = (record, index) => {
      state.invoiceIndex = index;
      state.ownerId = record.owner_id;
      state.invoiceVisible = true;
    };

    const successChange = () => {
      state.invoiceVisible = false;
      state.dataList.forEach((item, index) => {
        if (index == state.invoiceIndex) {
          getInvoiceData(item.owner_id).then((invoice) => {
            item.invoiceList = invoice;
          });
        }
      });
    };

    /* 监听开票类型变化 */
    const handleIssueTypeChange = (value, current) => {
      current.issue_type = value;
      current.splitList.forEach((item) => {
        item.issue_type = value;
        item.can_invoice_amount = item.apply_invoice_amount =
            value == 1
                ? item.can_invoice_amount_type1
                : item.can_invoice_amount_type2;
        item.tax_amount = getTaxAmount(
            item.apply_invoice_amount,
            item.tax_rate
        );
        item.unit_price = item.nopay_tax_price = getTaxAmount(
            item.apply_invoice_amount,
            item.tax_rate,
            true
        );
        if (item.splitList && item.splitList.length) {
          item.splitList.forEach((item2) => {
            item2.issue_type = value;
            item2.can_invoice_amount = item2.apply_invoice_amount =
                value == 1
                    ? item2.can_invoice_amount_type1
                    : item2.can_invoice_amount_type2;
            item2.tax_amount = getTaxAmount(
                item2.apply_invoice_amount,
                item2.tax_rate
            );
            item2.unit_price = item2.nopay_tax_price = getTaxAmount(
                item2.apply_invoice_amount,
                item2.tax_rate,
                true
            );
          });
        }
      });
      getCurrentAmountTotal(current);
    };

    /* 监听税率变化 */
    const handleTaxRateChange = (value, current, index) => {
      const currentItem = current.splitList[index];
      currentItem.tax_rate = value;
      const taxCode = state.taxRateList.find((item) => item.tax_rate == value);
      currentItem.tax_cost_name = taxCode.name;
      currentItem.tax_amount = getTaxAmount(
          currentItem.apply_invoice_amount,
          value
      );
      currentItem.unit_price = currentItem.nopay_tax_price = getTaxAmount(
          currentItem.apply_invoice_amount,
          value,
          true
      );
      // 更新里面包含的子账单的数据
      const subList = currentItem.splitList;
      if (subList && subList.length) {
        subList.forEach((item) => {
          item.tax_rate = value;
          item.tax_cost_name = currentItem.tax_cost_name;
          item.tax_amount = getTaxAmount(item.apply_invoice_amount, value);
          item.unit_price = item.nopay_tax_price = getTaxAmount(
              item.apply_invoice_amount,
              value,
              true
          );
        });
      }
      // 重新计算总账
      getCurrentAmountTotal(current);
    };

    /* 监听申请开票金额变化 */
    const handleApplyInvoiceAmountChange = (value, current, index) => {
      const currentItem = current.splitList[index];
      currentItem.apply_invoice_amount = value;
      currentItem.tax_amount = getTaxAmount(value, currentItem.tax_rate);
      currentItem.unit_price = currentItem.nopay_tax_price = getTaxAmount(
          value,
          currentItem.tax_rate,
          true
      );
      // 重新计算总账
      getCurrentAmountTotal(current);
    };

    /* 编辑发票信息 */
    const handleInvoiceEdit = (current) => {
      state.editContent = current;
      state.editVisible = true;
    };
    const handleInvoiceEditSuccess = (data) => {
      onSelectedRowChange([], []);
      const index = state.dataList.findIndex((item) => item.id == data.id);
      state.dataList[index] = JSON.parse(JSON.stringify(data));
      state.editVisible = false;
    };

    /* 获取初始的发票信息 */
    const resetData = () => {
      onSelectedRowChange([], []);
      state.initDataList = [];
      state.dataList = [];
    };
    const getInitInvoiceData = () => {
      resetData();
      state.loading = true;
      request
          .post("/org", "/invoice/build", {
            billIds: state.billIds,
          })
          .then((res) => {
            const {dataInit} = res;
            state.templateList = dataInit.templateList;
            state.mergeTypeList = dataInit.mergeType;
            state.issueTypeList = dataInit.issueType;

            // 后端返回的账单列表数据是不合并状态下的数据
            if (dataInit.templateBillList.length) {
              let renderData = {};
              if (state.templateId) {
                renderData = dataInit.templateBillList.find(
                    (item) => item.template_id == state.templateId
                );
              } else {
                renderData = dataInit.templateBillList[0];
                state.templateId = renderData.template_id;
              }
              state.currentTaxTemp = state.templateList.find(
                  (item) => item.id == state.templateId
              );
              state.taxRateList = state.currentTaxTemp.tax_rates;
              state.initDataList = renderData.billList;
              if (state.initDataList.length) {
                const index = state.initDataList.findIndex(
                    (item) => item.cost_type == "cost_8"
                );
                if (index === -1) {
                  // 没有滞纳金
                  state.mergeType = state.mergeTypeList[0].key;
                } else {
                  // 有滞纳金 只能选择合并展示并且对数据进行合并
                  state.mergeTypeList.splice(0, 1);
                  state.mergeType = state.mergeTypeList[0].key;
                }

                // 循环state.initDataList获取对应租客的发票抬头信息&&处理发票类型
                state.initDataList.forEach((item, index) => {
                  if (item.owner_id) {
                    getInvoiceData(item.owner_id)
                        .then((invoice) => {
                          item.invoiceList = invoice;
                          item.title_id = item?.owner_invoice_info?.id || undefined;
                          item.buyer_name = item?.owner_invoice_info?.title || undefined
                          getRenderDataList();
                        })
                        .catch(() => {
                          getRenderDataList();
                        });
                  }
                  // 处理发票类型
                  item.invoiceTypeList = dataInit.invoiceType;
                  if (state.template_id?.includes(state.templateId)) {
                    if (state.e_invoce_type) {
                      for (let j = 0; j < item.invoiceTypeList.length; j++) {
                        if (state.e_invoce_type == item.invoiceTypeList[j].key) {
                          state.invoce_id = j;
                        }
                      }
                    }
                  } else {
                    state.invoce_id = 0;
                  }
                  item.invoice_type =
                      item.invoice_type ||
                      item.invoiceTypeList[state.invoce_id].key;
                  item.invoiceTypeList = JSON.parse(
                      JSON.stringify(item.invoiceTypeList)
                  );
                  // 判断 非一般纳税人 的时候 需要将 增值税专用票禁用
                  if (item?.owner_invoice_info.company_type == 1) {
                    item.invoiceTypeList.forEach((invoice) => {
                      if (invoice.key == 2) {
                        invoice.disabled = true;
                        item.invoice_type = item.invoiceTypeList[0].key;
                      }
                    });
                  } else {
                    item.invoiceTypeList.forEach((invoice) => {
                      invoice.disabled = false;
                    });
                  }
                });
              }
            }
            state.loading = false;
          });
    };
    /**
     * 处理表格数据
     * 1. 不合并
     * 2. 同租客相同费用类型合并
     * 3. 同租客所有费用类型合并
     */
    const getRenderDataList = () => {
      // 切换合并状态时初始化数据
      state.dataList = [];
      state.selectedRowKeys = [];
      state.selectedRows = [];
      state.applyMoneyTotal = 0;
      if (state.mergeType == 1) {
        // 1 不合并
        state.dataList = state.initDataList.map((item) =>
            transfromTableItem(item)
        );
        state.applyInvoiceAmountDisabled = false;
      } else {
        // 合并
        state.applyInvoiceAmountDisabled = true;
        let dataList = [];
        //  2按租客分类 3按租客+费用类型分类
        let divideKey = "";
        if (state.mergeType == 2) {
          for (let i = 0; i < state.initDataList.length; i++) {
            if (state.initDataList[i].is_merge == 0) {
              state.merge = 0;
            }
          }
          if (state.merge == 0) {
            divideKey = ["cost_type", "owner_id"];
          } else {
            state.merge = 1;
            divideKey = ["owner_id"];
          }
        } else {
          state.merge = 1;
          divideKey = ["cost_type", "owner_id"];
        }
        let mergeObj = divideListByKey(divideKey); // 分类
        console.log("getRenderDataList mergeObj", toRaw(mergeObj));
        for (let key in mergeObj) {
          state.merge = 1;
          // 处理splitList相同费用类型合并；计算每一条的总金额、税等数据
          const listItem = transfromTableItem(mergeObj[key]);
          const costTypeObj = divideListByKey(
              ["cost_type"],
              listItem.splitList
          );
          listItem.splitList = [];
          for (let ctKey in costTypeObj) {
            costTypeObj[ctKey].total = costTypeObj[ctKey].splitList.length;
            const ctInvoiceTotal = getCanInvoiceAmountTotal(
                costTypeObj[ctKey].splitList
            );
            listItem.splitList.push({
              ...costTypeObj[ctKey],
              ...ctInvoiceTotal,
            });
          }
          const mergeInvoiceTotal = getCanInvoiceAmountTotal(
              listItem.splitList
          );
          dataList.push({
            ...listItem,
            ...mergeInvoiceTotal,
            issue_type: mergeInvoiceTotal.can_invoice_amount_type1 <= 0 ? 2 : 1,
          });
        }
        state.dataList = dataList;
      }
      console.log("getRenderDataList init", toRaw(state.initDataList));
      console.log("getRenderDataList render", toRaw(state.dataList));
    };
    const divideListByKey = (keyArr, list) => {
      let result = {};
      let costTypeObj = {};
      if (!list) {
        list = state.initDataList;
      }
      list.forEach((item) => {
        const itemKeyArr = keyArr.map((keyItem) => item[keyItem]);
        const keyStr = itemKeyArr.join("-");
        if (result[keyStr]) {
          result[keyStr].splitList.push(item);
        } else {
          result[keyStr] = {
            ...item,
            splitList: [item],
          };
        }
      });

      if (state.merge == 0) {
        for (let ctKey in result) {
          const itemKey = result[ctKey].owner_id;
          if (result[ctKey].is_merge != 0) {
            if (costTypeObj[itemKey]) {
              costTypeObj[itemKey].splitList = [
                ...costTypeObj[itemKey].splitList,
                ...result[ctKey].splitList,
              ];
            } else {
              costTypeObj[itemKey] = {
                ...result[ctKey],
              };
            }
          } else {
            costTypeObj[ctKey] = {
              ...result[ctKey],
            };
          }
        }
      } else {
        costTypeObj = result;
      }
      return costTypeObj;
    };

    // 列表数据整理
    const transfromTableItem = (item) => {
      let newItem = {
        key: item.id,
        bill_id: item.bill_id,
        id: item.id,
        // 购方信息
        owner_id: item.owner_id,
        owner_name: item.owner_name,
        owner_taxpayerIdNumber:
            item.owner_invoice_info && item.owner_invoice_info.tax_number
                ? item.owner_invoice_info.tax_number
                : "",
        owner_tel:
            item.owner_invoice_info && item.owner_invoice_info.tax_company_tel
                ? item.owner_invoice_info.tax_company_tel
                : "",
        owner_bank:
            item.owner_invoice_info && item.owner_invoice_info.tax_bank_name
                ? item.owner_invoice_info.tax_bank_name
                : "",
        owner_account:
            item.owner_invoice_info && item.owner_invoice_info.tax_bank_account
                ? item.owner_invoice_info.tax_bank_account
                : "",
        owner_address:
            item.owner_invoice_info && item.owner_invoice_info.tax_company_address
                ? item.owner_invoice_info.tax_company_address : "",
        // 售方信息
        seller_id:
            item.seller_info && item.seller_info.id ? item.seller_info.id : "",
        seller_name:
            item.seller_info && item.seller_info.company_name
                ? item.seller_info.company_name
                : "",
        seller_taxpayerIdNumber:
            item.seller_info && item.seller_info.taxpayer_number
                ? item.seller_info.taxpayer_number
                : "",
        seller_tel:
            item.seller_info && item.seller_info.phone
                ? item.seller_info.phone
                : "",
        seller_bank:
            item.seller_info && item.seller_info.bank
                ? item.seller_info.bank
                : "",
        seller_account:
            item.seller_info && item.seller_info.bank_account
                ? item.seller_info.bank_account
                : "",
        seller_address:
            item.seller_info && item.seller_info.address
                ? item.seller_info.address
                : "",
        // 发票信息
        invoice_number: item.invoice_number || "",
        invoice_code: item.invoice_code || "",
        invoice_time: item.invoice_time || "",
        // 备注
        remark: item.remark || "",
        //  费用类型
        cost_type: item.cost_type,
        cost_type_txt: item.cost_type_txt,
        is_merge: item.is_merge,
        // 税率数组
        tax_template_rate: item.tax_template_rate,

        // 发票类型
        invoice_type: item.invoice_type || undefined,
        invoiceTypeList: item.invoiceTypeList || [],
        // 发票抬头
        invoiceList: item.invoiceList || [],
        // 发票抬头默认数据
        title_id: item.title_id || undefined,
        buyer_name: item.buyer_name || undefined,
        // 发票抬头是否是一般纳税人
        company_type: item?.owner_invoice_info.company_type || undefined,
        //售方信息
        seller_info: item?.seller_info || undefined,
      };

      if (item.splitList && item.splitList.length) {
        // 合并
        newItem.splitList = item.splitList.map((subItem) =>
            transfromTableSubItem(subItem)
        );
      } else {
        // 未合并
        newItem.splitList = [transfromTableSubItem(item)];
      }
      // 开票类型
      const invoiceTotalData = getCanInvoiceAmountTotal(newItem.splitList);
      newItem.issue_type =
          invoiceTotalData.can_invoice_amount_type1 <= 0 ? 2 : 1;
      if (state.mergeType != 1) {
        handleIssueTypeChange(newItem.issue_type, newItem);
      }

      return {...newItem, ...invoiceTotalData};
    };
    const transfromTableSubItem = (item) => {
      let newItem = {
        // 固定信息
        key: item.id,
        bill_id: item.bill_id,
        subbill_id: item.id,
        village_id: item.village_id,
        build_id: item.build_id,
        build_bind: item.build_bind,
        owner_id: item.owner_id,
        seller_id: state.currentTaxTemp.seller_id,
        invoice_type: item.invoice_type || undefined,
        // 发票抬头
        title_id: item.title_id || undefined,
        buyer_name: item.buyer_name || undefined,
        cost_type: item.cost_type,
        cost_type_txt: item.cost_type_txt,
        is_merge: item.is_merge,
        // 规格
        specs: item.specs || "",
        // 单位
        invoice_unit: item.invoice_unit || "",
        // 数量合计
        total: item.total || 1,
        // 税率
        tax_template_rate: item.tax_template_rate,
        tax_rate: item.tax_rate || item.tax_template_rate[0].tax_rate,
        // 商品或服务名称
        tax_cost_name: item.tax_template_rate[0].name,
        // 金额相关
        receivable_payment: Number(item.receivable_payment), // 应收金额
        actual_retreat: Number(item.actual_retreat), // 需收金额
        actual_payment: Number(item.actual_payment), // 实收金额
        advanceAmount: Number(item.advanceAmount), // 提前开票的已开票金额
        actualAmount: Number(item.actualAmount), // 实收开票的已开票金额
      };
      // 开票类型：can_invoice_amount可开票金额  can_invoice_amount_type1可提前开票的金额  can_invoice_amount_type2可实收开票金额
      if (item.settle_status == 2) {
        // 已结清的开票类型固定为实收开票 --结清状态;1=未付款;2=已结清;3=部分结清;4=待退款;5=待收款
        newItem.can_invoice_amount_type1 = 0;
      } else {
        newItem.can_invoice_amount_type1 = getCanInvoiceAmount(
            newItem.actual_retreat,
            newItem.advanceAmount
        );
      }
      newItem.can_invoice_amount_type2 = getCanInvoiceAmountes(
          newItem.actual_payment,
          newItem.actualAmount,
          newItem.advanceAmount,
      );
      newItem.issue_type = newItem.can_invoice_amount_type1 <= 0 ? 2 : 1;
      // 申请开票金额 = 可开票金额
      newItem.apply_invoice_amount = newItem.can_invoice_amount =
          newItem[`can_invoice_amount_type${newItem.issue_type}`];
      // 税额
      newItem.tax_amount = getTaxAmount(
          newItem.apply_invoice_amount,
          newItem.tax_rate
      );
      // 商品或服务总金额（不含税）= 单价
      newItem.unit_price = newItem.nopay_tax_price = getTaxAmount(
          newItem.apply_invoice_amount,
          newItem.tax_rate,
          true
      );

      return newItem;
    };

    // 获取总的可开票金额
    const getCanInvoiceAmountTotal = (list) => {
      let can_invoice_amount_total = 0,
          can_invoice_amount_type1_total = 0,
          can_invoice_amount_type2_total = 0,
          tax_amount_total = 0,
          apply_invoice_amount_total = 0,
          nopay_tax_price_total = 0;
      list.forEach((item) => {
        can_invoice_amount_total = (
            Number(can_invoice_amount_total) + Number(item.can_invoice_amount)
        ).toFixed(2);
        can_invoice_amount_type1_total = (
            Number(can_invoice_amount_type1_total) +
            Number(item.can_invoice_amount_type1)
        ).toFixed(2);
        can_invoice_amount_type2_total = (
            Number(can_invoice_amount_type2_total) +
            Number(item.can_invoice_amount_type2)
        ).toFixed(2);
        tax_amount_total = (
            Number(tax_amount_total) + Number(item.tax_amount)
        ).toFixed(2);
        apply_invoice_amount_total = (
            Number(apply_invoice_amount_total) + Number(item.apply_invoice_amount)
        ).toFixed(2);
        nopay_tax_price_total = (
            Number(nopay_tax_price_total) + Number(item.nopay_tax_price)
        ).toFixed(2);
      });
      return {
        can_invoice_amount: can_invoice_amount_total,
        can_invoice_amount_type1: can_invoice_amount_type1_total,
        can_invoice_amount_type2: can_invoice_amount_type2_total,
        tax_amount: tax_amount_total,
        apply_invoice_amount: apply_invoice_amount_total,
        nopay_tax_price: nopay_tax_price_total,
        unit_price: nopay_tax_price_total,
      };
    };

    // 获取提前可开票金额
    const getCanInvoiceAmount = (amount1, amount2) => {
      if (!amount1) {
        return 0;
      }
      return (Number(amount1) - Number(amount2)).toFixed(2);
    };

    // 获取实收可开票金额
    const getCanInvoiceAmountes = (amount1, amount2, amount3) => {
      if (!amount1) {
        return 0;
      }
      let num = (Number(amount1) - Number(amount2) - Number(amount3)).toFixed(2)
      return num > 0 ? num : 0
    };

    // 获取税率 或 价税合计
    const getTaxAmount = (amount, rate, withoutRate = false) => {
      amount = Number(amount);
      rate = Number(rate);
      const rateAmount = ((amount * rate * 0.01) / (rate * 0.01 + 1)).toFixed(
          2
      );
      if (withoutRate) {
        return (amount - Number(rateAmount)).toFixed(2);
      }
      return rateAmount;
    };

    // 获取对应租客的开票信息
    const getInvoiceData = (owner_id) => {
      return new Promise((resolve, reject) => {
        request
            .get("/org", "/org/owner/invoice/title/all", {owner_id})
            .then((res) => {
              resolve(res.list);
            })
            .catch((err) => {
              reject(err);
            });
      });
    };

    // 提交数据申请开票
    const confirm = () => {
      submit();
    };

    const submit = () => {
      if (state.selectedRows.length == 0) {
        message.warning("请先勾选需要开发票的账单！");
        return;
      }
      console.log("-------------submit", toRaw(state.selectedRows));
      const dataList = JSON.parse(JSON.stringify(state.selectedRows));
      if (state.mergeType == 1) {
        // 不合并
        dataList.forEach((item) => {
          item.bill_ids = [item.splitList[0].bill_id];
          item.subbill_ids = [item.splitList[0].subbill_id];
          item.invoice_data = item.splitList.map((subItem) => ({
            cost_type: subItem.cost_type,
            tax_rate: subItem.tax_rate,
            can_invoice_amount: subItem.can_invoice_amount,
            apply_invoice_amount: subItem.apply_invoice_amount,
            tax_amount: subItem.tax_amount,
          }));
        });
      } else {
        // 合并
        dataList.forEach((item) => {
          let splitList = [];
          item.bill_ids = [];
          item.subbill_ids = [];
          item.invoice_data = item.splitList.map((listItem) => {
            listItem.splitList.forEach((subListItem) => {
              item.bill_ids.push(subListItem.bill_id);
              item.subbill_ids.push(subListItem.subbill_id);
              if (Number(subListItem.apply_invoice_amount) != 0) {
                splitList.push(subListItem);
              }
            });
            return {
              cost_type: listItem.cost_type,
              tax_rate: listItem.tax_rate,
              can_invoice_amount: listItem.can_invoice_amount,
              apply_invoice_amount: listItem.apply_invoice_amount,
              tax_amount: listItem.tax_amount,
            };
          });
          item.splitList = splitList;
        });
      };
      dataList.forEach((item) => {
        if (item?.file && item.file.length > 0) {
          item.file = item.file.map((fileData) => fileData.url)
        }
      });
      console.log("-------------submit222", toRaw(dataList));
      request
          .post("/org", "/invoice/handelBill", {
            tax_template_id: state.templateId,
            merge_type: state.mergeType,
            approval: state.actualApprove,
            approval_advance: state.advanceApprove,
            invoice_arr: dataList,
            needMsg: true,
          })
          .then((res) => {
            message.success(res.msg || "保存成功");
            request
                .post("/org", "/invoice/beforeVerify", {
                  billIds: state.billIds,
                })
                .then(() => {
                  getInitInvoiceData();
                })
                .catch((err) => {
                  if (err.code >= 50020) {
                    Modal.warning({
                      title: () => "提示",
                      content: () => err.msg,
                      onOk: () => {
                        $router.back();
                      },
                    });
                  }
                });
          })
          .catch((err) => {
            if (err.code == 12001) {
              Modal.confirm({
                title: () => "提示",
                content: () =>
                    err?.msg || "您需要先设置开票审批流程才能开具发票哦~",
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  if (window.__MICRO_APP_ENVIRONMENT__) {
                    window.microApp.forceDispatch({
                      type: "SetMicroPages",
                      microInfo: {
                        microId: `org_workApproval_manage_index`,
                        app: 'workApproval',
                        name: '管理审批',
                        url: `/approval/manage/index`,
                      }
                    })
                  }
                },
              });
            }
          });
    };

    const getadvance = () => {
      // 获取配置
      request
          .get("/org", "/approval/publish/process", {
            alias: "invoice_advance",
          })
          .then((res) => {
            state.advanceApprove = res.info.process; //判断是否开启
            state.advanceis_admin = res.info.is_admin; //判断是否有权限
            state.advance_id = res.info.id;
          });
    };

    const getactual = () => {
      // 获取配置
      request
          .get("/org", "/approval/publish/process", {
            alias: "invoice_receive",
          })
          .then((res) => {
            state.actualApprove = res.info.process; //判断是否开启
            state.actualis_admin = res.info.is_admin; //判断是否有权限
            state.actual_id = res.info.id;
          });
    };

    const getSetting = () => {
      if (state.apptype == 1) {
        getadvance();
      } else {
        getactual();
      }
    }

    const goSetting = (id, index) => {
      state.apptype = index;
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    const init = () => {
      const ids = $route.query.billIds;
      state.billIds = ids.split(",");
      if ($route.query.e_invoce_type) {
        state.e_invoce_type = $route.query.e_invoce_type;
      } else {
        state.e_invoce_type = 0;
      }
      if ($route.query.template_id) {
        const templateids = $route.query.template_id;
        state.template_id = templateids;
        state.templateId = parseInt(state.template_id[0]);
      }
      getadvance();
      getactual();
      getInitInvoiceData();
    };

    init();
    return {
      ...toRefs(state),
      COLUMNS,
      rowSelection,
      getInitInvoiceData,
      getRenderDataList,
      handleInvoiceTypeChange,
      handleIssueTypeChange,
      handleTaxRateChange,
      handleApplyInvoiceAmountChange,
      handleInvoiceEdit,
      handleInvoiceEditSuccess,
      submit,
      handleInvoiceChange,
      addInvoice,
      successChange,
      getadvance,
      getactual,
      goSetting,
      confirm,
      getCanInvoiceAmountes,
    };
  },
});

const COLUMNS = [
  {
    title: "购方信息",
    dataIndex: "owner_name",
    key: "owner_name",
    width: 180,
    fixed: "left",
  },
  {
    title: "发票抬头",
    dataIndex: "invoice_title",
    key: "invoice_title",
    width: 160,
  },
  {
    title: "发票类型",
    dataIndex: "invoice_type",
    key: "invoice_type",
    width: 160,
  },
  {
    title: "开票类型",
    dataIndex: "issue_type",
    key: "issue_type",
    width: 120,
  },
  {
    title: "费用类型",
    dataIndex: "splitList",
    key: "cost_type_txt",
    width: 160,
  },
  {
    title: "商品或服务名称",
    dataIndex: "splitList",
    key: "tax_cost_name",
    width: 160,
  },
  {
    title: "税率",
    dataIndex: "splitList",
    key: "tax_rate",
    width: 120,
  },
  {
    title: "可开票金额",
    dataIndex: "splitList",
    key: "can_invoice_amount",
    width: 160,
  },
  {
    title: "申请开票金额",
    dataIndex: "splitList",
    key: "apply_invoice_amount",
    width: 160,
  },
  {
    title: "税额",
    dataIndex: "splitList",
    key: "apply_tax_amount",
    width: 120,
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: 120,
    fixed: "right",
  },
];
</script>

<style lang="less" scoped>
.make-invoice {
  .header {
    background: #fff;
  }

  .content {
    margin: 10px;
  }
}
</style>
